package cn.com.cetccst.datacenter.collection.dao;

import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;

import java.util.List;

import cn.com.cetccst.datacenter.collection.entity.LocationRecordEntity;

//定位历史Dao
@Dao
public interface LocationRecordDao extends BaseDao<LocationRecordEntity> {

    @Query("select * from " + LocationRecordEntity.TABLE_NAME)
    List<LocationRecordEntity> getAll();

    @Query("DELETE FROM " + LocationRecordEntity.TABLE_NAME + " WHERE id NOT IN " +
            "(SELECT id FROM " + LocationRecordEntity.TABLE_NAME + " ORDER BY locate_time DESC LIMIT :count)")
    void deleteOver(int count);

    @Query("DELETE FROM " + LocationRecordEntity.TABLE_NAME + " WHERE locate_time < :timeThreshold")
    void deleteOlderThan(long timeThreshold);

    @Query("delete from " + LocationRecordEntity.TABLE_NAME)
    void clear();

    default void insertWithCleanup(LocationRecordEntity data) {
        // 插入新数据
        insert(data);
        cleanup();
    }

    @Transaction
    default void cleanup() {
        //缓存清理
        //定位历史记录最多保留3000条，90天。
        long time = System.currentTimeMillis() - (90L * 24 * 60 * 60 * 1000);
        deleteOlderThan(time);
        deleteOver(10);
    }
}
